package com.app.service.Impl;

import cn.hutool.core.lang.Console;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.app.common.RandomNumUtils;
import com.app.event.ComplaintEvent;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.ComplaintService;
import com.app.util.CommonHelp;
import com.app.vo.ComplainVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Random;
@Slf4j
@Service
public class ComplaintServiceImpl implements ComplaintService {
    @Autowired
    private ComplaintMapper complaintMapper;
    @Autowired
    private ComplaintUrlMapper complaintUrlMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public String addComplaint(ComplaintModel model) {
        String code = RandomNumUtils.getCode();
        while (selectSchedule(code) != null) {
            code = RandomNumUtils.getCode();
        }
        model.setCode(code);
        model.setCreateTime(CommonHelp.getNowTimestamp());
        if (model.getSituation() != null) {
            String[] situation = model.getSituation();
            StringBuilder s = new StringBuilder();
            for (int i = 0; i < situation.length; i++) {
                s.append(situation[i]).append(",");
            }
            model.setSituate(s.toString());
        }
        complaintMapper.insert(model);
        ComplainUrlModel complainUrlModel = new ComplainUrlModel();
        if (model.getPic() != null) {
            complainUrlModel.setComplainId(model.getId());
            String[] pic = model.getPic();
            StringBuilder s1 = new StringBuilder();
            for (int i = 0; i < pic.length; i++) {
                if (i == pic.length - 1) {
                    s1.append(pic[i]);
                } else {
                    s1.append(pic[i]).append(",");
                }
            }
            complainUrlModel.setUrl(s1.toString());
            complainUrlModel.setType(1);
            complainUrlModel.setComplainId(model.getId());
            complainUrlModel.setCreateTime(CommonHelp.getNowTimestamp());
            complaintUrlMapper.insert(complainUrlModel);
        }
        if (model.getPDF() != null) {
            complainUrlModel.setComplainId(model.getId());
            complainUrlModel.setComplainId(model.getId());
            String[] pdf = model.getPDF();
            StringBuilder s1 = new StringBuilder();
            for (int i = 0; i < pdf.length; i++) {
                if (i == pdf.length - 1) {
                    s1.append(pdf[i]);
                } else {
                    s1.append(pdf[i]).append(",");
                }
            }
            complainUrlModel.setUrl(s1.toString());
            complainUrlModel.setType(2);
            complainUrlModel.setComplainId(model.getId());
            complainUrlModel.setCreateTime(CommonHelp.getNowTimestamp());
            complaintUrlMapper.insert(complainUrlModel);
        }
        return code;
    }

    @Override
    public List<ComplaintModel> complaintList(Integer userId) {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<ComplaintModel> complaintModels = complaintMapper.selectList(queryWrapper);
        for (int i = 0; i < complaintModels.size(); i++) {
            if (complaintModels.get(i).getStatus() == 1) {
                complaintModels.get(i).setStatusText("待受理");
            }
            if (complaintModels.get(i).getStatus() == 2) {
                complaintModels.get(i).setStatusText("已办理");
            }
            if (complaintModels.get(i).getStatus() == 3) {
                complaintModels.get(i).setStatusText("驳回");
            }
            if (complaintModels.get(i).getStatus() == 4) {
                complaintModels.get(i).setStatusText("受理中");
            }
        }
        return complaintModels;
    }

    @Override
    public ComplaintModel selectSchedule(String code) {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        ComplaintModel model = complaintMapper.selectOne(queryWrapper);
        if (model == null) {
            return null;
        }
        model.setIdCardBack("");
        model.setIdCardFront("");
        QueryWrapper<ComplainUrlModel> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("complain_id", model.getId());
        List<ComplainUrlModel> complainUrlModels = complaintUrlMapper.selectList(queryWrapper1);
        for (int i = 0; i < complainUrlModels.size(); i++) {
            if (complainUrlModels.get(i).getType() == 1) {
                model.setPicUrl(complainUrlModels.get(i).getUrl());
            }
            if (complainUrlModels.get(i).getType() == 2) {
                model.setPdfUrl(complainUrlModels.get(i).getUrl());
            }
        }
        if (model.getSituate() != null && !model.getSituate().equals("")) {
            String situation = model.getSituate();
            String[] split = situation.split(",");
            if (split.length == 0) {
                return null;
            }
            String[] situationText = new String[split.length];
            List<CategoryModel> categoryModels = categoryMapper.selectList(null);
            for (int i = 0; i < split.length; i++) {
                for (int i1 = 0; i1 < categoryModels.size(); i1++) {
                    if (Integer.valueOf(split[i]).equals(categoryModels.get(i1).getId())) {
                        situationText[i] = categoryModels.get(i1).getName();
                    }
                }
            }
            model.setSituationText(situationText);
        }
        return model;
    }

    @Override
    public ComplaintModel selectSchedule(String code, Integer adminId) {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        ComplaintModel model = complaintMapper.selectOne(queryWrapper);
        if (model == null) {
            return null;
        }
        model.setIdCardBack("");
        model.setIdCardFront("");
        QueryWrapper<ComplainUrlModel> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("complain_id", model.getId());
        List<ComplainUrlModel> complainUrlModels = complaintUrlMapper.selectList(queryWrapper1);
        for (int i = 0; i < complainUrlModels.size(); i++) {
            if (complainUrlModels.get(i).getType() == 1) {
                model.setPicUrl(complainUrlModels.get(i).getUrl());
            }
            if (complainUrlModels.get(i).getType() == 2) {
                model.setPdfUrl(complainUrlModels.get(i).getUrl());
            }
        }
        if (model.getSituate() != null && !model.getSituate().equals("")) {
            String situation = model.getSituate();
            String[] split = situation.split(",");
            if (split.length == 0) {
                return null;
            }
            String[] situationText = new String[split.length];
            List<CategoryModel> categoryModels = categoryMapper.selectList(null);
            for (int i = 0; i < split.length; i++) {
                for (int i1 = 0; i1 < categoryModels.size(); i1++) {
                    if (Integer.valueOf(split[i]).equals(categoryModels.get(i1).getId())) {
                        situationText[i] = categoryModels.get(i1).getName();
                    }
                }
            }
            model.setSituationText(situationText);
        }
        AdminUserModel adminUserModel = adminUserMapper.selectById(adminId);
        UserModel userModel = userMapper.selectById(adminUserModel.getUserId());
        model.setProcessedName(userModel.getUserName());
        model.setProcessedMobile(userModel.getMobile());
        return model;
    }

    @Override
    public ComplaintModel selectDetail(Integer id) {
        ComplaintModel model = complaintMapper.selectById(id);
        if (model == null) {
            return null;
        }
        model.setIdCardBack("");
        model.setIdCardFront("");
        QueryWrapper<ComplainUrlModel> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("complain_id", model.getId());
        List<ComplainUrlModel> complainUrlModels = complaintUrlMapper.selectList(queryWrapper1);
        for (int i = 0; i < complainUrlModels.size(); i++) {
            if (complainUrlModels.get(i).getType() == 1) {
                model.setPicUrl(complainUrlModels.get(i).getUrl());
            }
            if (complainUrlModels.get(i).getType() == 2) {
                model.setPdfUrl(complainUrlModels.get(i).getUrl());
            }
        }
        if (model.getSituate() != null && !model.getSituate().equals("")) {
            String situation = model.getSituate();
            String[] split = situation.split(",");
            String[] situationText = new String[split.length];
            List<CategoryModel> categoryModels = categoryMapper.selectList(null);
            for (int i = 0; i < split.length; i++) {
                for (int i1 = 0; i1 < categoryModels.size(); i1++) {
                    if (Integer.valueOf(split[i]).equals(categoryModels.get(i1).getId())) {
                        situationText[i] = categoryModels.get(i1).getName();
                    }
                }
            }
            model.setSituationText(situationText);
        }
        return model;
    }

    @Override
    public ComplaintModel selectDetail(Integer id, Integer adminId) {
        ComplaintModel model = complaintMapper.selectById(id);
        if (model == null) {
            return null;
        }
        model.setIdCardBack("");
        model.setIdCardFront("");
        QueryWrapper<ComplainUrlModel> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("complain_id", model.getId());
        List<ComplainUrlModel> complainUrlModels = complaintUrlMapper.selectList(queryWrapper1);
        for (int i = 0; i < complainUrlModels.size(); i++) {
            if (complainUrlModels.get(i).getType() == 1) {
                model.setPicUrl(complainUrlModels.get(i).getUrl());
            }
            if (complainUrlModels.get(i).getType() == 2) {
                model.setPdfUrl(complainUrlModels.get(i).getUrl());
            }
        }
        if (model.getSituate() != null && !model.getSituate().equals("")) {
            String situation = model.getSituate();
            String[] split = situation.split(",");
            String[] situationText = new String[split.length];
            List<CategoryModel> categoryModels = categoryMapper.selectList(null);
            for (int i = 0; i < split.length; i++) {
                for (int i1 = 0; i1 < categoryModels.size(); i1++) {
                    if (Integer.valueOf(split[i]).equals(categoryModels.get(i1).getId())) {
                        situationText[i] = categoryModels.get(i1).getName();
                    }
                }
            }
            model.setSituationText(situationText);
        }
        model.setAdminId(adminId);
        return model;
    }

    @Override
    public void deleteComplaintList(Integer id) {
        complaintMapper.deleteById(id);
    }

    @Override
    public void examineComplaint(Integer id, Integer status, String remark, String handleRemark, String rejectRemark, AdminUserModel user) {
        ComplaintModel model = new ComplaintModel();
        if (user != null && user.getId() != null) {
            model.setProcessedId(user.getId());
        }
        model.setId(id);
        model.setStatus(status);
        if (handleRemark != null && status == 4) {//受理中
            model.setHandleRemark(handleRemark);
        }
        if (rejectRemark != null && status == 3) {//驳回
            model.setRejectRemark(rejectRemark);
        }
        if (remark != null && status == 2) {//办结
            model.setRemark(remark);
        }
        model.setProcessingTime(CommonHelp.getNowTimestamp());
        complaintMapper.updateById(model);
        if (model.getIsJiuquan() != null) {
            try {
                applicationContext.publishEvent(new ComplaintEvent(model));
            }catch (Exception e){
                log.info(e.toString());
            }
        }
    }

    @Override
    public ComplainVo selectComplaintList(Integer page, Integer limit, String keyWord, String selectCrtTime, AdminUserModel user) {
        page = (page - 1) * limit;
        String startTime = null;
        String endTime = null;
        if (selectCrtTime != null && !selectCrtTime.equals("")) {
            String[] split = selectCrtTime.split(",");
            startTime = split[0] + " 00:00:00";
            endTime = split[1] + " 23:59:59";
        }
        List<ComplaintModel> complaintModels = complaintMapper.selectComplaintList(page, limit, keyWord, startTime, endTime);
        for (int i = 0; i < complaintModels.size(); i++) {
            if (complaintModels.get(i).getAdminId() == null) {
                complaintModels.get(i).setAdminId(user.getId());
            }
            if (complaintModels.get(i).getProcessedId() != null && complaintModels.get(i).getProcessedId() != 1) {
                Integer adminId = complaintModels.get(i).getProcessedId();
                AdminUserModel adminUserModel = adminUserMapper.selectById(adminId);
                UserModel userModel = userMapper.selectById(adminUserModel.getUserId());
                complaintModels.get(i).setProcessedName(userModel.getUserName());
                complaintModels.get(i).setProcessedMobile(userModel.getMobile());
            } else if (complaintModels.get(i).getProcessedId() != null && complaintModels.get(i).getProcessedId() == 1) {
                complaintModels.get(i).setProcessedName("超级管理员");
                complaintModels.get(i).setProcessedMobile("");
            }
            if (complaintModels.get(i).getStatus() == 1) {
                complaintModels.get(i).setStatusText("待受理");
            }
            if (complaintModels.get(i).getStatus() == 2) {
                complaintModels.get(i).setStatusText("已办理");
            }
            if (complaintModels.get(i).getStatus() == 3) {
                complaintModels.get(i).setStatusText("驳回");
            }
            if (complaintModels.get(i).getStatus() == 4) {
                complaintModels.get(i).setStatusText("受理中");
            }
            if (complaintModels.get(i).getType() == 2) {
                complaintModels.get(i).setTypeText("⾮⼯程建设领域");
            }
            if (complaintModels.get(i).getType() == 1) {
                complaintModels.get(i).setTypeText("⼯程建设领域");
            }
            if (complaintModels.get(i).getIsContract() == 1) {
                complaintModels.get(i).setIsContractText("是");
            }
            if (complaintModels.get(i).getIsContract() == 2) {
                complaintModels.get(i).setIsContractText("否");
            }
        }

        int count = complaintMapper.selectComplaintCount(keyWord, startTime, endTime);
        ComplainVo vo = new ComplainVo();
        vo.setList(complaintModels);
        vo.setCount(count);
        return vo;
    }

    @Override
    public ComplainVo getComplaintList(Integer page, Integer limit, String keyword, String selectCrtTime, String isJiuquan) {
        page = (page - 1) * limit;
        String startTime = null;
        String endTime = null;
        if (selectCrtTime != null && !selectCrtTime.equals("")) {
            String[] split = selectCrtTime.split(",");
            startTime = split[0] + " 00:00:00";
            endTime = split[1] + " 23:59:59";
        }
        List<ComplaintModel> complaintModels = complaintMapper.getComplaintList(page, limit, keyword, startTime, endTime,isJiuquan);
        for (int i = 0; i < complaintModels.size(); i++) {
            if (complaintModels.get(i).getProcessedId() != null && complaintModels.get(i).getProcessedId() != 1) {
                Integer adminId = complaintModels.get(i).getProcessedId();
                AdminUserModel adminUserModel = adminUserMapper.selectById(adminId);
                UserModel userModel = userMapper.selectById(adminUserModel.getUserId());
                complaintModels.get(i).setProcessedName(userModel.getUserName());
                complaintModels.get(i).setProcessedMobile(userModel.getMobile());
            } else if (complaintModels.get(i).getProcessedId() != null && complaintModels.get(i).getProcessedId() == 1) {
                complaintModels.get(i).setProcessedName("超级管理员");
                complaintModels.get(i).setProcessedMobile("");
            }
            if (complaintModels.get(i).getStatus() == 1) {
                complaintModels.get(i).setStatusText("待受理");
            }
            if (complaintModels.get(i).getStatus() == 2) {
                complaintModels.get(i).setStatusText("已办理");
            }
            if (complaintModels.get(i).getStatus() == 3) {
                complaintModels.get(i).setStatusText("驳回");
            }
            if (complaintModels.get(i).getStatus() == 4) {
                complaintModels.get(i).setStatusText("受理中");
            }
            if (complaintModels.get(i).getType() == 2) {
                complaintModels.get(i).setTypeText("⾮⼯程建设领域");
            }
            if (complaintModels.get(i).getType() == 1) {
                complaintModels.get(i).setTypeText("⼯程建设领域");
            }
            if (complaintModels.get(i).getIsContract() == 1) {
                complaintModels.get(i).setIsContractText("是");
            }
            if (complaintModels.get(i).getIsContract() == 2) {
                complaintModels.get(i).setIsContractText("否");
            }
        }

        int count = complaintMapper.getComplaintCount(keyword, startTime, endTime,isJiuquan);
        ComplainVo vo = new ComplainVo();
        vo.setList(complaintModels);
        vo.setCount(count);
        return vo;
    }

    @Override
    public List<UserModel> whiteList() {
        return complaintMapper.whiteList();
    }

    @Override
    public List<ComplaintModel> examineComplaintList(Integer status) {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        if (status != null && status != 0) {
            queryWrapper.eq("status", status);
        }
        if (status == null || status == 0) {
            queryWrapper = null;
        }
        List<ComplaintModel> complaintModels = complaintMapper.selectList(queryWrapper);
        for (int i = 0; i < complaintModels.size(); i++) {
            if (complaintModels.get(i).getStatus() == 1) {
                complaintModels.get(i).setStatusText("待受理");
            }
            if (complaintModels.get(i).getStatus() == 2) {
                complaintModels.get(i).setStatusText("已办理");
            }
            if (complaintModels.get(i).getStatus() == 3) {
                complaintModels.get(i).setStatusText("驳回");
            }
            if (complaintModels.get(i).getStatus() == 4) {
                complaintModels.get(i).setStatusText("受理中");
            }
        }
        return complaintModels;
    }

    @Override
    public List<ComplaintModel> examineComplaintList(Integer status, Integer adminId) {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        if (status != null && status != 0) {
            queryWrapper.eq("status", status);
        }
        if (status == null || status == 0) {
            queryWrapper = null;
        }
        List<ComplaintModel> complaintModels = complaintMapper.selectList(queryWrapper);
        for (int i = 0; i < complaintModels.size(); i++) {
            complaintModels.get(i).setAdminId(adminId);
            if (complaintModels.get(i).getStatus() == 1) {
                complaintModels.get(i).setStatusText("待受理");
            }
            if (complaintModels.get(i).getStatus() == 2) {
                complaintModels.get(i).setStatusText("已办理");
            }
            if (complaintModels.get(i).getStatus() == 3) {
                complaintModels.get(i).setStatusText("驳回");
            }
            if (complaintModels.get(i).getStatus() == 4) {
                complaintModels.get(i).setStatusText("受理中");
            }
        }
        return complaintModels;
    }

    @Override
    public Object selectHandle(Integer id) {
        ComplaintModel model = complaintMapper.selectById(id);
        QueryWrapper<ComplainUrlModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("complain_id", model.getId());
        ComplainUrlModel complainUrlModel = complaintUrlMapper.selectOne(queryWrapper);
        if (complainUrlModel != null && complainUrlModel.getUrl() != null) {
            model.setPdfUrl(complainUrlModel.getUrl());
        }
        return model;
    }

    @Override
    public List<ComplaintModel> selectByUserId(Integer id) {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        List<ComplaintModel> complaintModels = complaintMapper.selectList(queryWrapper);
        for (int i = 0; i < complaintModels.size(); i++) {
            QueryWrapper<ComplainUrlModel> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("complain_id", complaintModels.get(i).getId());
            ComplainUrlModel complainUrlModel = complaintUrlMapper.selectOne(queryWrapper1);
            complaintModels.get(i).setPdfUrl(complainUrlModel.getUrl());
        }
        return complaintModels;
    }

    @Override
    public int selectAllCount() {
        return complaintMapper.selectCount(null);
    }

    @Override
    public int selectStatusCount() {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 2);
        return complaintMapper.selectCount(queryWrapper);
    }

    @Override
    public int selectByType(Integer type) {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        return complaintMapper.selectCount(queryWrapper);
    }

    @Override
    public int selectByStatus(Integer status) {
        QueryWrapper<ComplaintModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", status);
        return complaintMapper.selectCount(queryWrapper);
    }
    @Override
    public void pushStatus(ComplaintModel source) {
        String result2 = HttpRequest.post("http://127.0.0.1:9111/jiuquan/complaint/doProtectionState")
                .header(Header.USER_AGENT, "Hutool http")//头信息，多个头信息多次调用此方法即可
                .header(Header.CONTENT_TYPE,"application/json")
                .body(JSON.toJSONString(source))//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        Console.log(result2);
    }

    @Override
    public ComplaintModel getById(Integer id) {
        ComplaintModel complaintModel = complaintMapper.selectById(id);
        QueryWrapper<CategoryModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", 10);
        List<CategoryModel> categoryModelList = categoryMapper.selectList(queryWrapper);
        if (complaintModel.getProcessedId() != null && complaintModel.getProcessedId() != 1) {
            Integer adminId = complaintModel.getProcessedId();
            AdminUserModel adminUserModel = adminUserMapper.selectById(adminId);
            UserModel userModel = userMapper.selectById(adminUserModel.getUserId());
            if (userModel != null) {
                complaintModel.setProcessedName(userModel.getUserName());
                complaintModel.setProcessedMobile(userModel.getMobile());
            }
        } else if (complaintModel.getProcessedId() != null && complaintModel.getProcessedId() == 1) {
            complaintModel.setProcessedName("超级管理员");
            complaintModel.setProcessedMobile("");
        }
        if (complaintModel.getStatus() == 1) {
            complaintModel.setStatusText("待受理");
        }
        if (complaintModel.getStatus() == 2) {
            complaintModel.setStatusText("已办理");
        }
        if (complaintModel.getStatus() == 4) {
            complaintModel.setStatusText("受理中");
        }
        if (complaintModel.getType() != null) {
            if (complaintModel.getType() == 2) {
                complaintModel.setTypeText("⾮⼯程建设领域");
            }
            if (complaintModel.getType() == 1) {
                complaintModel.setTypeText("⼯程建设领域");
            }
        }
        if (complaintModel.getIsContract() != null) {
            if (complaintModel.getIsContract() == 1) {
                complaintModel.setIsContractText("是");
            }
            if (complaintModel.getIsContract() == 2) {
                complaintModel.setIsContractText("否");
            }
        }
        return complaintModel;
    }
}
